package cn.gson.crm.controller.beforesale;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONObject;

import cn.gson.crm.model.dao.AttachmentDao;
import cn.gson.crm.model.dao.DemandDao;
import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.OpportunityDao;
import cn.gson.crm.model.entity.Attachment;
import cn.gson.crm.model.entity.Demand;
import cn.gson.crm.model.entity.Demand;
import cn.gson.crm.model.entity.Demand;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.entity.SalesOpportunity;
import cn.gson.crm.service.UploadService;

@Controller
@RequestMapping("demand")
public class DemandController {

	@Autowired
	DemandDao demandDao;
	
	@Autowired
	EmployeeDao empDao;
	
	@Autowired
	OpportunityDao oppDao;
	
	@Autowired
	UploadService uploadService;
	
	@Autowired
	AttachmentDao attDao;
	
	@RequestMapping
	public String demand() {
		return "beforesale/demand";
	}
	
	//加载需求列表中的表格
	@RequestMapping({"demandform","demandform/{id}"})
	public String demandForm(@PathVariable(required=false) Long id,Model model){
		if (id != null) {
			model.addAttribute("d",demandDao.findOne(id));
		}
		return "beforesale/demand/demandform";
	}
	
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> list(@RequestParam(defaultValue = "1")int page,
			@RequestParam(defaultValue = "10")int rows,
			HttpServletRequest req
			){
		Map<String, Object> data = new HashMap<>();
		PageRequest pr = new PageRequest(page - 1, rows, new Sort(Direction.DESC,"id"));
		Page<Demand> com = null;
		//先从session里获取当前登录用户的数据
		Employee emp = (Employee)req.getSession().getAttribute("employee");
		//判断职位(roles)，如果是销售人员则显示他所关联的客户有关的需求
		if (emp.getRole().getRoleName().equals("销售员")) {
			Long empid = emp.getId();
			com = demandDao.findByEmp(empid,pr);
		}else {
			//如果是管理人员，则显示所有未删除的
			com = demandDao.findByIsDelete(false,pr);
		}

		data.put("rows", com.getContent());
		data.put("total", com.getTotalElements());
		return data;
	}
	
	@RequestMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject save(Demand demand,Long saleid,Long atts[],BindingResult br) {
		JSONObject result = new JSONObject();
		if (br.hasErrors()) {
			result.put("err", "校验失败！");
		}else {
			SalesOpportunity opp = oppDao.findOne(saleid);
			demand.setSalesOpp(opp);
			

			//总的附件
			List<Attachment> lst = new ArrayList<>();
			
			//原先已关联的附件
			if (demand.getId() != null) {
				List<Attachment> list = demandDao.findOne(demand.getId()).getAttachment();
				if (list != null) {
					for (Attachment attachment : list) {
						lst.add(attachment);
					}
				}
			}
			
			//从页面获取新的附件
			if (atts != null && atts.length > 0) {
				for (Long attachment : atts) {
					Attachment att = attDao.findOne(attachment);
					lst.add(att);
				}
			}
			//创建demand与附件的关联
			demand.setAttachment(lst);
			demandDao.save(demand);
			result.put("success", true);
		}
		return result;
	}

	/**
	 * 不在数据库删除此条信息
	 * 只是将是否删除（isDelete）这个字段改成true，代表已删除
	 * @param id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	public Map<String, Object> delete(@PathVariable Long id) {
		
		Map<String, Object> data = new HashMap<>();
		
		try {
			Demand demand = demandDao.findOne(id);
			demand.setDelete(true);
			demandDao.save(demand);
			data.put("success", true);
			
		} catch (Exception e) {
			e.printStackTrace();
			data.put("success", false);
			data.put("errorMsg", e.getMessage());
		}
		return data;
	}
	
	
	
}
